package com.j48.entrancegurad.controller;

import com.j48.entrancegurad.model.Host;
import com.j48.entrancegurad.model.Host_openid;
import com.j48.entrancegurad.model.User;
import com.j48.entrancegurad.service.WxService;
import com.j48.entrancegurad.tools.HttpRequest;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.j48.entrancegurad.service.IUserService;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class WxController {
    @Autowired
    private WxService wxService;
    @Autowired
    private IUserService userService;
    @Autowired
    private com.j48.entrancegurad.service.IHostService hostService;
    /**
     * 获取用户的openID
     *
     * @param
     * @param request
     * @return
     */
    @RequestMapping("/wxLogin")
    @ResponseBody
    public String selectHost(HttpServletRequest request) {
        String code = null;
        String appid = "appid=wx914080e4a1b895b1";
        String secret = "secret=7d569ec93e65cb26a23b7fb52b266057";
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String grant_type = "grant_type=authorization_code";

        code = "js_code="+request.getParameter("code");
        String param=appid+"&"+secret+"&"+code+"&"+grant_type;
        HttpRequest requests = new HttpRequest();
        //S表示获取到微信小程序中的唯一标识
        String s = requests.sendPost(url, param);
       String [] str=s.split(",");
        String str1[]=str[1].split("\"");
        String openId=str1[3];
        request.getSession().setAttribute("openId",openId);
//        System.out.println(request.getSession().getAttribute("openId")+"111");
        HttpSession session=request.getSession();
        String sessionId=session.getId();
//        System.out.println(sessionId+"1111");
        Host_openid ho=new Host_openid(openId);
            User user =new User();
        if (wxService.HostOpenId(ho)!=null){
            user.setUser_open_id(openId);
        }else {
            wxService.InsertOpenid(ho);
            return sessionId+":false";
        }
        User user2=userService.selectByToken(user);
        if (user2==null){
            return sessionId+":false";
        }
        int host_id=user2.getUser_host_id();
        Host host=new Host();
        host.setHost_id(host_id);
        Host host1=hostService.selectById(host);
        List<Host> hostList=new ArrayList<>();
        hostList.add(host1);
        request.getSession().setAttribute("HostList",hostList);
      return sessionId+":true";
   }


}

